﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace T02Client
{
    class TcpClient
    {
        static void Main(string[] args)
        {
            Socket client;
            byte[] buf = new byte[1024];
            string input;
            //1建立套接字信息
            //获取远程服务器的ip地址
            IPAddress remote = IPAddress.Parse("10.104.55.194");
            //端口号实际范围1~65535，1~1024为系统保留，避开一些端口号，例如3306为默认mysql端口号，4000为qq端口
            IPEndPoint iep = new IPEndPoint(remote, 13000);

            //2发送请求连接，服务器响应或拒绝或网络出现故障
            try
            {    //建立（IPV4流方式 Tcp协议）套接字
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                    ProtocolType.Tcp);
                //与远程服务器建立连接
                client.Connect(iep);
            }
            catch (SocketException e)
            {
                Console.WriteLine("无法连接服务端");
                return;//终止程序，不带任何值的返回
            }
            //3数据交换
            while (true)
            {
                input = Console.ReadLine();
                if (input == "exit") { break; }
                //发送数据
                client.Send(Encoding.ASCII.GetBytes(input));
                //接收应答
                int rec = client.Receive(buf);
                //输出
                Console.WriteLine(Encoding.ASCII.GetString(buf,
                    0, rec));
            }
            //释放资源
            Console.WriteLine("断开服务器连接");
            client.Close();
        }
    }
}
